from django import forms
import base64


class HostForm(forms.Form):
    ansible_ssh_host = forms.GenericIPAddressField(required=True)
    ansible_ssh_pass = forms.CharField(max_length=1024, required=True)
    ansible_ssh_user = forms.CharField(max_length=255,required=True)
    ansible_ssh_port = forms.IntegerField(
        max_value=65535, min_value=1, initial=22,required=False)

    @classmethod
    def valid(cls, hosts: list):
        """
        验证主机列表，合法主机加入到valid_host列表中，非法主机加入到invalid列表中
        :param hosts: 主机列表
        """
        invalid_hosts = []
        valid_hosts = []
        for host in hosts:
            #host['ansible_ssh_pass']=base64.decodestring(str(host['ansible_ssh_pass']))
            f = cls(host)
            if not f.is_valid():
                invalid_hosts.append({
                    "host": host,
                    "error": f.errors
                })
            else:
                valid_hosts.append(host)
        result = {
            'valid': valid_hosts,
            'invalid': invalid_hosts
        }
        return result